package net.ixion.portal.web.tag;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.log4j.Logger;

/**
 * 
 * @author 贵源
 * 自定义集合迭代器
 * View里的对象操作无外乎就是2种
 * 	1：单独对象，我们可以直接获取对象及其属性进行展示
 * 	2：集合对象，我们可以使用本类提供的标签进行迭代即可
 */
@SuppressWarnings("rawtypes")
public class IteratorTag extends BodyTagSupport {

	/**
	 * 序列号版本号
	 */
	private static final long serialVersionUID = 1L;
	protected static final Logger logger = Logger.getRootLogger();

	private String name;
	private Iterator item;
	private String type;

	public void setCollection(Collection collection) {
		if (collection.size() > 0) {
			item = collection.iterator();
		}
	}

	public int doStartTag() {
		if (item == null) {
			return SKIP_BODY;
		} else {
			return continueNext(item);
		}
	}

	@SuppressWarnings("deprecation")
	private int continueNext(Iterator item2) {
		if (item2.hasNext()) {
			pageContext
					.setAttribute(name, item2.next(), PageContext.PAGE_SCOPE);
			return EVAL_BODY_TAG;
		}
		return SKIP_BODY;
	}

	public int doAfterBody() {
		return continueNext(item);
	}
	public int doEndTag() {
		try {
			if(bodyContent != null){
				bodyContent.writeOut(bodyContent.getEnclosingWriter());
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return EVAL_PAGE;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Iterator getItem() {
		return item;
	}

	public void setItem(Iterator item) {
		this.item = item;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
}
